package com.xiaozhameng.threadlocal;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 多线程操作方式
 */
public class LockTest {

    public static void main(String[] args) {
        Lock lock = new ReentrantLock();

        lock.lock();

        for (int i = 0; i < 3; i++) {
            new Thread(()->{
                boolean tryLock = lock.tryLock();
                try {
                    process();
                }finally {
                    if (tryLock){
                        lock.unlock();
                    }
                }
            }).start();
        }
    }

    private static void process(){
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
